package cn.dapeng.interview;

import lombok.Getter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 题目：写一个固定容量的同步容器，拥有put和get方法，以及getCount方法
 * 能够支持2个生产者和10个消费者的阻塞调用
 * <p>
 * 使用wait和notifyAll来实现
 * <p>
 * <p>
 * 同步容器：多线程往里装，多线程往外取
 */
public class SynchronizeContainer_T01<T> {

    private final List<T> list = new ArrayList<T>();

    private final static int MAX_SIZE = 10;

    @Getter
    private int count = 0;

    public synchronized void put(T t) {
        while (count == MAX_SIZE) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        list.add(t);
        this.notifyAll();
        count++;
    }

    public synchronized T get() {
        while (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        T t = list.remove(0);
        this.notifyAll();
        count--;
        return t;
    }

    public static void main(String[] args) throws IOException {
        SynchronizeContainer_T01<Integer> object = new SynchronizeContainer_T01<>();
        for (int i = 0; i < 2; i++) {
            final int o = i;
            new Thread(() -> {
               for (int j = 0; j < 100; j++) {
                   object.put(o);
                   System.out.println(Thread.currentThread().getName() + " put :: " + o);
               }
            }, "t" + i).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true) {
                    System.out.println(Thread.currentThread().getName() + " get :: " + object.get());
                }
            }, "T" + i).start();
        }

        System.in.read();
    }

}
